package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session){

        Map<String, Object> map = new HashMap<>();
        map.put("client_id","3725880087");
        map.put("client_secret","415b67c6cd8cc290d0baa023696a30ea");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);

        String s = HttpUtils.postRequest("https://api.weibo.com/oauth2/access_token", null, map);
        SocialUser socialUser = JSON.parseObject(s, SocialUser.class);

        // 知道了当前是哪个社交用户，
        // 登陆或注册社交用户
        R authologin = memberFeignService.authologin(socialUser);

        if(authologin.getCode() == 0){
            MemberRespVo data = authologin.getData(new TypeReference<MemberRespVo>() {});
            // 作用域不能只是当前域
            // 使用json的方式存储
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://gulimall.com";
        }else{
            return "redirect:http://auth.gulimall.com/login.html";
        }





    }
}
